<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title></title>
  <style>
    * {
      margin: 0;
      padding: 0
    }

    ul {
      list-style: none
    }

    body {
      background-color: #333;
    }

    .nav {
      width: 800px;
      height: 42px;
      margin: 100px auto;
      background: url(images/rss.png) right center no-repeat;
      background-color: #fff;
      border-radius: 10px;
      position: relative;
    }

    .nav li {
      width: 83px;
      height: 42px;
      text-align: center;
      line-height: 42px;
      float: left;
      cursor: pointer;
    }

    .nav span {
      position: absolute;
      top: 0;
      left: 0;
      width: 83px;
      height: 42px;
      background: url(images/cloud.gif) no-repeat;
    }

    ul {
      position: relative;
    }
  </style>
</head>

<body>
  <div class="nav">
    <span id="cloud"></span>
    <ul id="navBar">
      <li>北京校区</li>
      <li>上海校区</li>
      <li>广州校区</li>
      <li>深圳校区</li>
      <li>武汉校区</li>
      <li>关于我们</li>
      <li>联系我们</li>
      <li>招贤纳士</li>
    </ul>
  </div>
  <script>
    let cloud = document.querySelector("#cloud");
    let li = document.querySelectorAll("#navBar li");

    // es6 es6中的this调用的是windwo并不是调用当前的this
    // mouseoverHandle = () => {
    //   fn(cloud, this.offsetLeft)
    //   console.log(this);
    //   console.log(this.offsetLeft);
    // }

    // es5
    function mouseoverHandle() {
      fn(cloud, this.offsetLeft)
    }

    let last = 0;

    function clickHandle() {
      last = this.offsetLeft;
    }

    function mouseoutHandle() {
      fn(cloud, last);
    }

    for (let i = 0; i < li.length; i++) {
      // 鼠标移入
      li[i].onmouseover = mouseoverHandle;
      // 鼠标点击
      li[i].onclick = clickHandle;
      // 鼠标离开
      li[i].onmouseout = mouseoutHandle;
    }

    // 封装点击事件移动函数
    //设置任意的一个元素,移动到指定的目标位置
    fn = (element, target) => {
      clearInterval(element.timeId);
      //定时器的id值存储到对象的一个属性中
      element.timeId = setInterval(function () {
        //获取元素的当前的位置,数字类型
        var current = element.offsetLeft;
        //每次移动的距离
        var step = (target - current) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        current += step;
        if (Math.abs(current - target) > Math.abs(step)) {
          element.style.left = current + "px";
        } else {
          //清理定时器
          clearInterval(element.timeId);
          //直接到达目标
          element.style.left = target + "px";
        }
      }, 20);
    }
  </script>
</body>

</html>